import { changeCount, delSelect, getCartList } from '@/api/cart'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },

    toggleCheck (state, goodsId) {
      const res = state.cartList.find(item => item.goods_id === goodsId)
      res.isChecked = !res.isChecked
    },

    toggleAllCheck (state, boolean) {
      state.cartList.forEach(item => {
        item.isChecked = boolean
      })
    },

    changeCount (state, { goodsId, value }) {
      const obj = state.cartList.find(item => item.goods_id === goodsId)
      obj.goods_num = value
    }
  },
  actions: {
    async getCartAction (a) {
      const { data } = await getCartList()
      // console.log(data)
      data.list.forEach(element => {
        element.isChecked = true
      })
      a.commit('setCartList', data.list)
    },

    async changeCountAction (context, obj) {
      const { goodsId, value, skuId } = obj
      context.commit('changeCount', {
        goodsId,
        value
      })
      await changeCount(goodsId, value, skuId)
    },

    // 删除购物车数据
    async delAction (context) {
      const delList = context.getters.selCartList
      // console.log(delList.map(i => i.id))
      const delId = delList.map(i => i.id)
      await delSelect(delId)
      Toast('删除成功')

      context.dispatch('getCartAction')
    }
  },

  getters: {
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },

    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },

    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },

    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => {
        return sum + item.goods_num * item.goods.goods_price_min
      }, 0).toFixed(2)
    },

    isAllChecked (state) {
      const list = state.cartList.filter(item => item.isChecked === true)
      // console.log(list.length === state.cartList.length)
      return list.length === state.cartList.length
    }
  }
}
